<template>
  <div class="question-detail-container">
    <!-- 面包屑导航
    <el-breadcrumb class="breadcrumb" separator="/">
      <el-breadcrumb-item :to="{ path: '/question' }">题库</el-breadcrumb-item>
      <el-breadcrumb-item>{{ route.query.libraryName }}</el-breadcrumb-item>
    </el-breadcrumb> -->

    <!-- 顶部操作区域 -->
    <div class="top-actions">
      <div class="left-actions">
        <el-select v-model="selectValue" class="filter-select" @change="filterQuestions">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加题目
        </el-button>

        <el-button @click="exportToWord" :loading="exporting">
          <el-icon><Document /></el-icon>导出Word
        </el-button>
      </div>
      
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索题目内容"
          class="search-input"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 题目列表区域 -->
    <question-list 
      :questions="filteredQuestions"
      @edit="handleEdit"
      @delete="handleDelete"
    />

    <!-- 添加编辑抽屉 -->
    <el-drawer
      v-model="dialogVisible"
      :title="editForm.id ? '编辑题目' : '添加题目'"
      direction="rtl"
      size="40%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      class="edit-drawer"
    >
      <question-edit 
        :question="editForm"
        :disabled="disabled"
        @save="handleSave"
        @cancel="handleCancel"
      />
    </el-drawer>
  </div>
</template>

<script setup name="QuestionDetail">
import { ref, computed, onMounted } from 'vue';
import { Edit, Delete, Search, Plus, Document } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { getLibraryQuestions, saveQuestions, updateQuestion, removeQuestionFromLibrary } from '../../api/question'
import QuestionEdit from '../../components/question/QuestionEdit.vue'
import QuestionList from '../../components/question/QuestionList.vue'

const route = useRoute()
const selectValue = ref("all")
const options = [{
  value: "all", 
  label: "全部题型"
},{
  value: "SINGLE_CHOICE",
  label: "单选题"
}, {
  value: "MULTIPLE_CHOICE",
  label: "多选题"
}, {
  value: "TRUE_FALSE",
  label: "判断题" 
}, {
  value: "FILL_BLANK",
  label: "填空题"
}, {
  value: "SHORT_ANSWER",
  label: "简答题"
}, {
  value: "READING",
  label: "综合题"
}]

const libraryId = ref(route.query.libraryId)
const questions = ref([])

// 搜索关键词
const searchKeyword = ref('')

// 搜索处理函数
const handleSearch = () => {
  // 如果搜索框为空，显示所有题目
  if (!searchKeyword.value.trim()) {
    return questions.value
  }
  
  // 根据关键词过滤题目
  return questions.value.filter(question => 
    question.stem.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
    (question.analysis && question.analysis.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
    (question.knowledgePoints && question.knowledgePoints.some(point => 
      point.toLowerCase().includes(searchKeyword.value.toLowerCase())
    ))
  )
}

// 更新过滤后的题目列表计算属性
const filteredQuestions = computed(() => {
  let filtered = questions.value
  
  // 先按搜索关键词过滤
  if (searchKeyword.value.trim()) {
    filtered = handleSearch()
  }
  
  // 再按题型过滤
  if (selectValue.value !== 'all') {
    filtered = filtered.filter(q => q.questionType === selectValue.value)
  }
  
  return filtered
})

// 获取题目类型标签样式
const getQuestionTypeTag = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': 'primary',
    'MULTIPLE_CHOICE': 'success',
    'TRUE_FALSE': 'info',
    'FILL_BLANK': 'warning',
    'SHORT_ANSWER': 'danger',
    'READING': 'danger' 
  }
  return typeMap[type] || 'info'
}

// 获取题目类型标签文本
const getQuestionTypeLabel = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'READING': '综合题'
  }
  return typeMap[type] || type
}

// 获取难度标签
const getDifficultyTag = (difficulty) => {
  const difficultyMap = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return difficultyMap[difficulty] || 'info'
}

// 获取难度标签文本
const getDifficultyLabel = (difficulty) => {
  const difficultyMap = {
    1: '简单',
    2: '中等',
    3: '困难'
  }
  return difficultyMap[difficulty] || '未知'
}

// 导出状态
const exporting = ref(false)

// 获取题目列表
const getQuestionDetail = async () => {
  try {
    const res = await getLibraryQuestions(libraryId.value)
    questions.value = res.data
  } catch (error) {
    console.error('获取题目失败:', error)
    ElMessage.error('获取题目失败，请重试')
  }
}

// 筛选题目
const filterQuestions = () => {
  // 触发computed重新计算
  console.log('筛选类型:', selectValue.value)
}

// 导出Word文档
const exportToWord = async () => {
  try {
    exporting.value = true
    
    // 准备导出数据
    const exportData = filteredQuestions.value.map((question, index) => {
      let questionText = `${index + 1} `
      
      // 根据题型添加标题
      switch(question.questionType) {
        case 'SINGLE_CHOICE':
          questionText += '[单选题] '
          break
        case 'MULTIPLE_CHOICE':
          questionText += '[多选题] '
          break
        case 'TRUE_FALSE':
          questionText += '[判断题] '
          break
        case 'FILL_BLANK':
          questionText += '[填空题] '
          break
        case 'SHORT_ANSWER':
          questionText += '[简答题] '
          break
        case 'READING':
          questionText += '[综合题] '
          break
      }
      
      // 根据不同题型处理内容
      if (question.questionType === 'READING') {
        // 综合题题先显示文章内容
        questionText += `\n${question.passage}\n\n`
        
        // 处理子题目
        if (question.subQuestions && question.subQuestions.length > 0) {
          question.subQuestions.forEach((subQ, subIndex) => {
            questionText += `(${subQ.score}分) 第${subIndex + 1}小题：${subQ.stem}\n`
            
            // 如果子题目有选项
            if (subQ.options && subQ.options.length > 0) {
              subQ.options.forEach(option => {
                questionText += `${option.optionId}. ${option.content}\n`
              })
            }
            
            questionText += `答案：${subQ.answer}\n`
            if (subQ.analysis) {
              questionText += `解析：${subQ.analysis}\n`
            }
            questionText += '\n'
          })
        }
      } else if (question.questionType === 'FILL_BLANK') {
        // 填空题处理
        questionText += `${question.stem}\n`
        if (question.blanks) {
          const blanks = question.blanks.split('|')
          blanks.forEach((blank, blankIndex) => {
            questionText += `第${blankIndex + 1}空：${blank}\n`
          })
        }
      } else {
        // 其他题型处理
        questionText += question.stem + '\n'
        
        // 添加选项
        if (question.options && question.options.length > 0) {
          question.options.forEach(option => {
            questionText += `${option.optionId}. ${option.content}\n`
          })
        }
        
        // 添加答案
        questionText += '答案：'
        if (question.questionType === 'SINGLE_CHOICE') {
          questionText += question.answer
        } else if (question.questionType === 'MULTIPLE_CHOICE') {
          questionText += question.answers?.[0] || ''
        } else if (question.questionType === 'TRUE_FALSE') {
          questionText += question.answer === 'TRUE' ? '对' : '错'
        } else {
          questionText += question.answers?.[0] || question.answer || ''
        }
        questionText += '\n'
      }
      
      // 添加难度
      questionText += `难易程度：${getDifficultyLabel(question.difficulty)}\n`
      
      // 添加解析
      if (question.analysis && question.questionType !== 'READING') {
        questionText += `答案解析：${question.analysis}\n`
      }
      
      // 添加知识点
      if (question.knowledgePoints && question.knowledgePoints.length > 0) {
        questionText += `知识点：${question.knowledgePoints.join('；')}\n`
      }
      
      return questionText + '\n'
    }).join('\n')
    
    // 创建Blob对象
    const blob = new Blob([exportData], { type: 'application/msword;charset=utf-8' })
    
    // 创建下载链接
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `${route.query.libraryName}_${options.find(item => item.value === selectValue.value).label}.doc`
    
    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exporting.value = false
  }
}

// 编辑相关的数据
const dialogVisible = ref(false)
const editForm = ref({})
const saving = ref(false)
const disabled = ref(false)

// 处理编辑按钮点击
const handleEdit = (question) => {
  disabled.value = true
  editForm.value = JSON.parse(JSON.stringify(question)) // 深拷贝
  dialogVisible.value = true
}

// 处理删除按钮点击
const handleDelete = async (question) => {
  ElMessage.warning('正在删除题目，请稍等...')
  const res = await removeQuestionFromLibrary(libraryId.value, question.id)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    questions.value = questions.value.filter(q => q.id !== question.id)
  } else {                                
    ElMessage.error('删除失败')
  }
}

// 处理新增按钮点击
const handleAdd = () => {
  disabled.value = false
  dialogVisible.value = true
  editForm.value = {
    id: '',
    stem: '',
    options: [],
    answers: [],
    analysis: '',
    knowledgePoints: [],
    difficulty: 1,
    questionType: 'SINGLE_CHOICE',
    blanks: '',
    answer: null,
    passage: null,
    subQuestions: null
  }
}

// 处理保存
const handleSave = async (formData) => {
  try {
    saving.value = true
    
    // 如果是更新操作
    if (formData.id) {
      const data = JSON.stringify(formData)
      await updateQuestion(formData.id, data)
      ElMessage.success('更新成功')
      
      // 更新本地数据
      const index = questions.value.findIndex(q => q.id === formData.id)
      if (index !== -1) {
        questions.value[index] = { ...formData }
      }
    } 
    // 如果是新增操作
    else {
      const res = await saveQuestions(libraryId.value, JSON.stringify([formData]))
      if (res.data && res.data.length > 0) {
        formData.id = res.data[0]
        questions.value.push({ ...formData })
      }
      ElMessage.success('保存成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(error.message || '保存失败，请重试')
  } finally {
    saving.value = false
    disabled.value = true
  }
}

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false
  disabled.value = true
}

onMounted(() => {
  getQuestionDetail()
})
</script>

<style scoped>
.question-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding: 10px 0;
}

.top-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.left-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-box {
  max-width: 300px;
  min-width: 200px;
}

.search-input {
  width: 100%;
}

.filter-select {
  width: 120px;
}

.questions-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.question-card:hover {
  transform: translateY(-2px);
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
}

.question-index {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.question-type-tag {
  margin-right: 8px;
}

.difficulty-tag {
  font-size: 12px;
}

.question-content {
  margin-bottom: 20px;
}

.question-stem {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 16px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  display: flex;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f5f7fa;
  transition: background-color 0.3s ease;
}

.option-item:hover {
  background-color: #e6e8eb;
}

.option-id {
  font-weight: bold;
  color: #409EFF;
}

.true-false-options {
  margin-top: 12px;
}

.fill-blank-content {
  margin: 16px 0;
}

.fill-blank-stem {
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.fill-blank-answers {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.blank-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.blank-index {
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
}

.blank-answer {
  color: #67c23a;
}

.answer-section {
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
}

.answer-title {
  color: #409EFF;
  font-weight: bold;
}

.answer-content {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.answer-area {
  margin-bottom: 16px;
}

.analysis-area {
  margin-bottom: 16px;
  line-height: 1.6;
}

.knowledge-points {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.knowledge-tag {
  margin-right: 8px;
}

.formatted-answer {
  white-space: pre-wrap;
  line-height: 1.6;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .top-actions {
    flex-direction: column;
    gap: 12px;
  }
  
  .left-actions {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .search-box {
    width: 100%;
    max-width: 100%;
  }
  
  .question-card {
    margin-bottom: 16px;
  }
}

/* 编辑图标样式 */
.edit-icon {
  position: absolute;
  top: 16px;
  right: 32px;
  opacity: 0;
  transition: opacity 0.3s ease;
}
/* 删除图标样式 */
.delete-icon {
  position: absolute;
  top: 16px;
  right: 16px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.question-card:hover .edit-icon {
  opacity: 1;
}

.edit-btn {
  font-size: 30px;
  color: #409EFF;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.edit-btn:hover {
  color: #66b1ff;
  background-color: #ecf5ff;
}

/* 删除按钮样式 */
.delete-btn {
  font-size: 30px;
  color: #f56c6c;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  color: #f56c6c;
  background-color:  #ecf5ff;
}

/* 抽屉样式 */
.edit-drawer {
  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;
  }

  :deep(.el-drawer__body) {
    padding: 20px;
    overflow-y: auto;
  }

  :deep(.el-form) {
    height: calc(100vh - 170px);
    overflow-y: auto;
    padding-right: 16px;
  }
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 修改表单内部的滚动条样式 */
.edit-form::-webkit-scrollbar {
  width: 6px;
}

.edit-form::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.edit-form::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 综合题题样式 */
.reading-passage {
  margin-bottom: 24px;
}

.passage-content {
  font-size: 15px;
  line-height: 1.8;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
  white-space: pre-wrap;
}

.sub-questions {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.sub-question {
  padding: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.sub-question-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.sub-question-index {
  font-weight: bold;
  color: #409EFF;
}

.sub-question-score {
  color: #f56c6c;
}

.sub-question-stem {
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 12px;
}

.sub-question-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.sub-question-answer {
  margin-bottom: 12px;
}

.sub-question-analysis {
  margin-bottom: 12px;
}

.sub-question-title {
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 4px;
}

.sub-question-content {
  padding-left: 16px;
}

.blank-answer-item {
  margin-bottom: 8px;
  color: #67c23a;
}

/* 响应式样式补充 */
@media screen and (max-width: 768px) {
  .passage-content {
    padding: 12px;
  }

  .sub-question {
    padding: 12px;
  }
}

/* 编辑对话框中的填空题和综合题题样式 */
.blank-edit {
  display: flex;
  gap: 12px;
  align-items: center;
}

.option-edit {
  display: flex;
  gap: 12px;
  align-items: center;
}

.option-edit .el-input {
  flex: 1;
}

.remove-btn {
  flex-shrink: 0;
}

.sub-question-edit {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.sub-question-edit .sub-question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.sub-question-edit .sub-question-index {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.sub-question-edit .el-form-item {
  margin-bottom: 16px;
}

/* 响应式样式补充 */
@media screen and (max-width: 768px) {
  .sub-question-edit {
    padding: 12px;
  }
}

/* 综合题子题目容器样式 */
.sub-questions-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.add-sub-question-btn {
  display: flex;
  justify-content: center;
  padding: 16px 0;
  border-top: 1px dashed #dcdfe6;
  margin-top: 8px;
}
</style>